<template>
  <div class="ElAddArticle">
    <!-- 头部 -->
    <div>
      <el-card class="box-card">
        <div slot="header">
          <myel-header text1="首页" text2="文章管理"></myel-header>
        </div>
        <div>
          <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="80px">
            <!-- 标题 -->
            <el-form-item label="标题" prop="title">
              <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <!-- 内容-富文本 -->
            <el-form-item label="内容" prop="content" class="editor">
              <quillEditor :options="editorOption" v-model="ruleForm.content"/>
            </el-form-item>
            <!-- 封面 -->
            <el-form-item label="封面">
              <el-radio-group v-model="ruleForm.cover.type">
                <el-radio label="0">无图</el-radio>
                <el-radio label="1">单图</el-radio>
                <el-radio label="3">三图</el-radio>
                <el-radio label="-1">自动</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 封面显示的上传图 -->
            <el-form-item v-if="ruleForm.cover.type > 0">
              <span v-if="ruleForm.cover.type==='1'" @click="onupimgs = true" class="imgdeyang">
                <img
                  v-if="ruleForm.cover.images.length !== 0"
                  :src="ruleForm.cover.images"
                  class="imgdeyang"
                >
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </span>
              <span
                v-for="i in Number(ruleForm.cover.type)"
                :key="i"
                v-else
                @click="onupimgs = true"
                class="imgdeyang"
              >
                <img
                  v-if="ruleForm.cover.images.length !== 0"
                  :src="ruleForm.cover.images[i-1]"
                  class="imgdeyang"
                  @click="huoquid(i-1)"
                >
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </span>
            </el-form-item>
            <!-- 弹出层 -->
            <el-dialog
              title="请选择素材"
              append-to-body
              :visible.sync="onupimgs"
              width="75%"
              :before-close="handleClose"
            >
              <!-- 组件------------------------------------------------------------ -->
              <my-el-images iskai :type="ruleForm.cover.type" @zigofu="zigofu"></my-el-images>
            </el-dialog>
            <!-- 频道 -->
            <el-form-item label="频道" prop="channel_id">
              <el-select v-model="ruleForm.channel_id" placeholder="请选择">
                <el-option
                  v-for="item in mychannels"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 俩按钮 -->
            <el-form-item v-if="!isyesornoid">
              <el-button type="primary" @click="submitForm('ruleForm')">发表</el-button>
              <el-button @click="resetForm('ruleForm')">存入草稿</el-button>
            </el-form-item>
            <!-- 编辑 -->
            <el-form-item v-else>
              <el-button type="primary" @click="bianjiForm(ruleForm)">编辑</el-button>
              <el-button @click="resetForm('ruleForm')">存入草稿</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 接口
import { pusharticles, upAddarticle, getArticleDetail, updateArticle } from '@/api/articles.js'
// 头部组件
import MyelHeader from './MyelHeader.vue'
// images组件
import MyElImages from './MyElImages.vue'
// 富文本
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'ElAddArticle',
  data () {
    return {
      // 判断是否传入id
      isyesornoid: false,
      // 当前文章id
      isonid: '',
      ididid: '',
      // 弹出框
      onupimgs: false,
      // 存入草稿or发表
      draft: true,
      // 默认封面选择
      radio: '1',
      // 频道数据
      mychannels: [],
      value: '',
      // 富文本配置项
      editorOption: {
        placeholder: '',
        modules: {
          // 工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      // 表单数据
      ruleForm: {
        title: '',
        content: '',
        channel_id: '',
        cover: {
          type: '',
          images: []
        }
      },
      // 验证
      rules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 5, message: '长度最少5个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 20, message: '最少20个字', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '请选择频道', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.isrouteid()
    this.articlesGoods()
  },
  methods: {
    // 判断是否带有id
    async isrouteid () {
      if (this.$route.params.id) {
        this.isyesornoid = true
        this.isonid = this.$route.params.id
        // // 调用接口
        const { data } = await getArticleDetail(this.$route.params.id)
        if (data.message === 'OK') {
          this.ruleForm = data.data
          this.ruleForm.cover.type = `${data.data.cover.type}`
        } else {
          this.$message.error('操作失败')
        }
      } else {
        this.isyesornoid = false
      }
    },
    // 点击编辑
    async bianjiForm (res) {
      // 编辑or草稿 false or true
      // this.draft
      // 当前文章id
      // this.isonid
      try {
        const { data } = await updateArticle(
          this.isonid,
          { draft: this.draft },
          {
            title: this.ruleForm.title,
            content: this.ruleForm.content,
            channel_id: this.ruleForm.channel_id,
            cover: {
              type: Number(this.ruleForm.cover.type),
              images: this.ruleForm.cover.images
            }
          }
        )
        if (data.message === 'OK') {
          this.$router.push('/articles')
          this.$message({
            message: '文章编辑成功',
            type: 'success'
          })
        } else {
          this.$message.error('文章编辑失败')
        }
      } catch (error) {
        this.$message.error('文章编辑失败')
      }
    },
    async articlesGoods () {
      // 获取频道数据
      const { data: { data: { channels } } } = await pusharticles()
      this.mychannels = channels
    },
    // 发表
    submitForm (ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.draft = false
          this.submitorreset()
          this.ruleForm.cover.images = []
          this.draft = true
          this.$refs.ruleForm.resetFields()
        } else {
          return false
        }
      })
    },
    // 存入草稿
    resetForm (ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.draft = true
          this.submitorreset()
          this.ruleForm.cover.images = []
          this.$refs.ruleForm.resetFields()
        } else {
          return false
        }
      })
    },
    // 调用接口
    async submitorreset () {
      try {
        const { data } = await upAddarticle(
          {
            draft: this.draft
          }, {
            title: this.ruleForm.title,
            content: this.ruleForm.content,
            channel_id: this.ruleForm.channel_id,
            cover: {
              type: Number(this.ruleForm.cover.type),
              images: this.ruleForm.cover.images
            }
          }
        )
        if (data.message === 'OK') {
          this.$router.push('/articles')
          this.$message({
            message: '文章发布成功',
            type: 'success'
          })
        } else {
          this.$message.error('文章发布失败')
        }
      } catch (error) {
        this.$message.error('文章发布失败')
      }
    },
    // 弹出层
    handleClose () {
      this.onupimgs = false
    },
    // 子过来的imgurl
    zigofu (item) {
      if (item) {
        this.onupimgs = false
        if (this.ruleForm.cover.type === '1') {
          this.ruleForm.cover.images = [item]
        } else {
          if (this.ruleForm.cover.images.length < 3) {
            this.ruleForm.cover.images.push(item)
          } else {
            this.ruleForm.cover.images.splice(this.ididid, 1, item)
          }
        }
        this.$message({
          message: '上传成功',
          type: 'success'
        })
      } else {
        this.$message.error('上传失败')
      }
    },
    huoquid (id) {
      this.ididid = id
    }
  },
  components: {
    MyelHeader,
    quillEditor,
    MyElImages
  }
}
</script>

<style lang="less" scoped>
.editor {
  /deep/ .el-form-item__content {
    line-height: normal;
  }
}
// 封面选择的上传图样式
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #ccc;
  margin-right: 5px;
}
.imgdeyang {
  width: 100px;
  height: 100px;
}
</style>
